package cn.bugstack.mybatis.session;

import java.util.HashMap;
import java.util.Map;

import cn.bugstack.mybatis.binding.MapperRegistry;
import cn.bugstack.mybatis.datasource.druid.DruidDataSourceFactory;
import cn.bugstack.mybatis.datasource.pooled.PooledDataSourceFactory;
import cn.bugstack.mybatis.datasource.unpooled.UnpooledDataSourceFactory;
import cn.bugstack.mybatis.mapping.Enviornment;
import cn.bugstack.mybatis.mapping.MappedStatement;
import cn.bugstack.mybatis.transaction.jdbc.JdbcTransactionFactory;
import cn.bugstack.mybatis.type.TypeAliasRegistry;

/**
 * description: mybatis配置类
 * taskId：
 * <pre>
 * change history:
 * date             defect#             person                comments
 * ---------------------------------------------------------------------
 * 2024/11/25       ********         zhaochaoyue        create file
 * </pre>
 *
 * @author: zhaochaoyue
 * @date: 2024/11/25 16:22
 * @copyright: 2024
 */
public class Configuration {
    
    //环境
    protected Enviornment enviornment;

    /**
     * 注册映射机
     */
    protected MapperRegistry mapperRegistry = new MapperRegistry(this);

    /**
     * 映射的语句sql 存放到map中
     */
    protected final Map<String, MappedStatement> mappedStatements = new HashMap<>();

    /**
     * 类型别名注册机放入configuration中
     */
    protected final TypeAliasRegistry typeAliasRegistry = new TypeAliasRegistry();

    public Configuration() {
        //通过注册机 jdbc 和 duird  放入configuration
        typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class);
        typeAliasRegistry.registerAlias("DRUID", DruidDataSourceFactory.class);
        typeAliasRegistry.registerAlias("UNPOOLED", UnpooledDataSourceFactory.class);
        typeAliasRegistry.registerAlias("POOLED", PooledDataSourceFactory.class);
    }

    public <T> void addMapper(Class<T> type){
        mapperRegistry.addMapper(type);
    }
    //sql的id是key value是对应的对象
    public void addMappedStatement(MappedStatement ms){
        mappedStatements.put(ms.getId(),ms);
    }

    public MapperRegistry getMapperRegistry() {
        return mapperRegistry;
    }

    public void setMapperRegistry(MapperRegistry mapperRegistry) {
        this.mapperRegistry = mapperRegistry;
    }

    public Map<String, MappedStatement> getMappedStatements() {
        return mappedStatements;
    }
    
    public <T> T getMapper(Class<T> type,SqlSession sqlSession){
        return mapperRegistry.getMapper(type,sqlSession);
    }
    
    public MappedStatement getMappedStatement(String id){
        return mappedStatements.get(id);
    }

    public TypeAliasRegistry getTypeAliasRegistry() {
        return typeAliasRegistry;
    }

    public Enviornment getEnviornment() {
        return enviornment;
    }

    public void setEnviornment(Enviornment enviornment) {
        this.enviornment = enviornment;
    }
}
